<?php

namespace common\biz;

/**
 * 验证码表
 *
 * @author peng.huang
 */
class IdentifycodeBiz extends \common\base\BaseBiz {

    /**
     * 构造函数
     */
    public function __construct() {
        $this->dao = static::getDao('common\dao\IdentifycodeDao');
    }

    /**
     * 返回验证码
     * 
     * @param strng $name [手机号\Email]
     * @param int $keyType [钥匙类型(0=手机注册、1=手机无密码登录、2=手机找回密码、3=email激活、3=email找回密码)]
     * @return array
     */
    public function findCode($name, $keyType) {
        $where = array('name' => $name, 'keytype' => $keyType, 'status' => 0, 'expiredAt>' => date('Y-m-d H:i:s', time()));
        return $this->dao->findOne('id,keycode', $where, ' id desc');
    }

    /**
     * 保存验证码
     * 
     * @param object $entity [实体对象]
     * @param int $expired [有效期，单位为秒]
     * @return boolean
     */
    public function saveKeyCode($entity, $expired = 600) {
        $where = array('name' => $entity->loginname, 'keytype' => $entity->keytype, 'expiredAt>' => date('Y-m-d H:i:s', time()));
        $existRow = $this->dao->findOne('id', $where);
        if (!empty($existRow)) {
            return $entity->appendError('loginname', '请不要频繁发送短信验证请求');
        }

        // 保存验证码
        $data = array('name' => $entity->loginname,
            'keycode' => $entity->keycode,
            'keytype' => $entity->keytype,
            'status' => 0,
            'expiredAt' => date('Y-m-d H:i:s', time() + $expired),
        );
        if (-1 === $this->dao->save($data)) {
            return $this->appendError('loginname', '短信验证码生成失败。');
        }

        return TRUE;
    }

}
